package com.superzlc.vjoy.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class BroadcastServer {

	public static void main(String[] args) throws Exception {
		new BroadcastServer().receiveRequest();
	}

	Thread tserver;
	public void startup() {
		tserver = new Thread() {
			public void run() {
				receiveRequest();
			}
		};
		tserver.start();
		isStartup = true;
	}

	public void shutdown() {
		isStartup = false;
		if (socket != null)
			socket.close();
		tserver.interrupt();
	}

	private boolean isStartup = false;
	DatagramSocket socket;

	public BroadcastServer() {
	}

	// 接收到特定广播，然后发送特定响应
	public void receiveRequest() {
		try {
			socket = new DatagramSocket(Constants.PORT_FOR_BROADCAST);
		} catch (SocketException e) {
			System.out.println("广播服务端打开端口出错，" + e.getMessage());
			e.printStackTrace();
			return;
		}
		// socket.setSoTimeout(READ_TIMEOUT_MS);
		byte[] bytes4receive = new byte[1024];
		DatagramPacket packet4receive = new DatagramPacket(bytes4receive, bytes4receive.length);

		while(isStartup) {

			// 接收
			System.out.println("开始接收广播。。。");
			try {
				socket.receive(packet4receive);
			} catch (IOException e) {
				System.out.println("广播服务端接收请求出错，" + e.getMessage());
				e.printStackTrace();
				continue;
			}
			String ip = packet4receive.getAddress().getHostAddress();
			String str = new String(packet4receive.getData(), 0, packet4receive.getLength());
			System.out.println("接收到来自" + ip + "的请求:" + str);

			// 处理请求
			String ack;
			if (Constants.DATA_REQUEST_SERVER_IP.equals(str)) {
				ack = Constants.DATA_REQUEST_ACK_SERVER_IP;
			} else {
				ack = Constants.DATA_REQUEST_ACK_NULL;
			}

			// 发送
			try {
				byte[] bytes4send = ack.getBytes();
				DatagramPacket packet4send = new DatagramPacket(bytes4send, bytes4send.length,
						InetAddress.getByName(ip), packet4receive.getPort());
				socket.send(packet4send);
			} catch(IOException e) {
				System.out.println("广播服务端发送响应出错，" + e.getMessage());
				e.printStackTrace();
				continue;
			}

		}
		socket.close();
	}
}
